tags:

views:

58

answers:

2

Hi,

given a plain text document with several lines like:

c48 7.587 7.39
c49 7.508 7.345983
c50 5.8 7.543
c51 8.37454546 7.34

I need to add some info 2 spaces after the end of the line, so for each line I would get:

c48 7.587 7.39  def
c49 7.508 7.345983  def
c50 5.8 7.543  def
c51 8.37454546 7.34  def

I need to do this for thousands of files. I guess this is possible to do with sed, but do not know how to. Any hint? Could you also give me some link with a tutorial or table for this cases?

Thanks

+2  A: 
for file in ${thousands_of_files} ; do
    sed -i ".bak" -e "s/$/  def/" file
done

The key here is the search-and-replace s/// command. Here we replace the end of the line $ with 2 spaces and your string.

Find the sed documentation at http://sed.sourceforge.net/#docs

Chen Levy
thanks a lot. just one question, doing this on OSX, why does the character "^M" appear?
Werner
IIRC, the end-of-line - EOL end character(s) in Unix, Mac and Windows are all different. `sed` is a Unix utility so it uses the Unix convention, i.e. ending each line with Carriage Return - CR (^M), while macs uses Line Feed - LF (^L), Windows BTW uses CR,LF. Thepoint is that you are left with the Unix EOL character. I am not a Mac guru, but there should be a utility to fix this. On my Linux box there is `dos2unix` and `unix2dos`, but if you can't find such a tool, try using `tr '\r' '\f'` to get a similar effect.
Chen Levy
One note, Macs used CR (^M) ('\r') up until OS X, at which point they switched to LF (^L) ('\n'). UNIX has always used LF (^L). You are correct when you said that Windows uses CRLF (^M^L) ("\r\n").
amertune
+1  A: 

if all your files are in one directory

sed -i.bak 's/$/  def/' *.txt

to do it recursive (GNU find)

find /path -type f -iname '*.txt' -exec sed -i.bak 's/$/  def/' "{}" +;

you can see here for introduction to sed

Other ways you can use,

awk

for file in *
do
  awk '{print $0" def"}' $file >temp
  mv temp "$file"
done 

Bash shell

for file in *
do
  while read -r line
  do
      echo "$line def"
  done < $file >temp
  mv temp $file
done
ghostdog74
What's `+;`? I always use `\;`. The bash manpage doesn't make me any wiser.
Thomas
its there in GNU `find's` man page. its equivalent to `xargs`
ghostdog74
hi, the awk one is nice. just a short question, how can awk '{print $0" def"}' $file >temp be applied to a concrete line number of the file?
Werner
@werner, for line number, aka record number, use `NR`, eg `awk 'NR==3{..}' file` means do for line 3
ghostdog74
thanks a lot, i should drink less coffee :)
Werner