Home > front end >  insert a line with file which has sed command in linux
insert a line with file which has sed command in linux

Time:10-18

I am trying to insert line in a file which will have a sed command to insert a line in another file Like below for eg : want to add this line sed -i '1s/^/insideFile\n/' secondFile.sh to 65th line of firstfile.txt

I tried:

sed -i '65s/^/\'sed -i \'1s/^/insideFile\n/\' secondFile.sh\'\n/' firstfile.sh

but not able to escape the '

also tried

sed -i "65s/^/'sed -i "1s/^/topLine\n/" $FILE_HOME_LOCAL_FILE'\n/" secondFile.sh

but got sed: -e expression #1, char 18: unknown option to `s

CodePudding user response:

You may use this sed:

sed -i.bak "65s~^~sed -i '1s/^/insideFile\\\\n/' secondFile.sh\\n~" firstfile.sh

Note:

  • Use of alternate delimiter ~ to avoid escaping /
  • use of double quotes for your sed command to avoid escaping single quotes
  • use of \\\\ to insert a single \
  • use of \\n inside double quotes to insert a line break

Alternatively with i (insert) instead of s (substitute):

sed -i.bak "65i\\
sed -i '1s/^/insideFile\\\\n/' secondFile.sh\\
" firstfile.sh

Cleanest solution would be to create a sed script like this thus avoiding all quoting and extra escaping:

cat ins.sed
65i\
sed -i '1s/^/insideFile\\n/' secondFile.sh

Then use it as:

sed -i.bak -f ins.sed firstfile.sh

CodePudding user response:

While sed allows you to do these things, it becomes a bit cumbersome when slashes and other control characters are involved. So it might be beneficial to use awk instead for this one:

$ awk '(FNR==65){print "sed -i \0421s/^/insideFile\\n/\042 secondFile.sh"}1' firstfile.txt > firstfile.new
$ mv firstfile.new > firstfile.txt

There are inplace possibilities, but if you come to think of it. Inplace is nothing more than making a temp to rename afterwards. This is exactly what sed is doing.

CodePudding user response:

I want to add this line sed -i '1s/^/insideFile\n/' secondFile.sh to 65th line of firstfile.txt

A scripted solution:

#!/bin/bash

## uncomment to make sure firstfile.txt has at least 65 (e.g. 66) lines
# for index in {1..66}; do    
#  echo -e "$index" >> firstfile.txt
# done

# prepare the insert text, escaping the newline character twice
text="sed -i '1s/^/insideFile\\\\n/'"

# append to 65th line
sed -i '' "65i\\
$text
" firstfile.txt
  • Related