View Single Post
  #6   (View Single Post)  
Old 7th November 2010
drl's Avatar
drl drl is offline
Port Guard
 
Join Date: May 2008
Posts: 19
Default

Hi.

Here is an alternate method for sed, as well as an awk solution. The center code is the important part, the beginning lines are to show the environment of execution:
Code:
#!/usr/bin/env bash

# @(#) s2       Demonstrate append string to specific line with awk, sed.

# Section 1, setup, pre-solution.
# Infrastructure details, environment, commands for forum posts. 
# Uncomment export command to test script as external user.
# export PATH="/usr/local/bin:/usr/bin:/bin"
set +o nounset
pe() { for i;do printf "%s" "$i";done; printf "\n"; }
pl() { pe;pe "-----" ;pe "$*"; }
C=$HOME/bin/context && [ -f $C ] && . $C sed
awk -V
set -o nounset
pe

FILE=${1-data1}

# Section 2, display input file.
# Display sample of data file, with head & tail as a last resort.
pl " Contents of data file $FILE:"
cat $FILE

# Section 3, solution.
pl " Results, awk:"
awk '
NR == 2 { print $0, 2; next }
        { print }
' $FILE

pl " Results, sed:"
sed '2s/$/ 2/' $FILE

exit 0
producing:
Code:
% ./s2

Environment: LC_ALL = C, LANG = C
(Versions displayed with local utility "version")
OS, ker|rel, machine: OpenBSD, 4.2, i386
GNU bash 3.2.17
sed - ( /usr/bin/sed Aug 28 2007 )
awk version 20041222


-----
 Contents of data file data1:
1
3
4

-----
 Results, awk:
1
3 2
4

-----
 Results, sed:
1
3 2
4
Best wishes ... cheers, drl
Reply With Quote