Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add at the end of the line with sed

Tags:

bash

sed

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

like image 695
Open the way Avatar asked Mar 25 '10 14:03

Open the way


People also ask

How do I append with sed?

To get help on a specific command, run $sed -?. The 'n' command instructs sed to print out each line of the file and print it to the screen. This is not suitable for editing files. Instead, use 'r' or 'w' to append the new data after each line or just write them verbatim to a file.


2 Answers

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
like image 129
ghostdog74 Avatar answered Sep 21 '22 12:09

ghostdog74


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

like image 35
Chen Levy Avatar answered Sep 24 '22 12:09

Chen Levy