简体   繁体   中英

Replace character in file at specific line number

I have index.html file

I want line# 88 which looks like this: <h1>Test Page 1</h1>

To be like this: <h1>Test Page 10</h1>

Tried basic procedures such as:

sed -i '88s/1/10' index.html

sed -i ‘88|\(.*\)|                 <h1>Test Page 10</h1>\1|' index.html

but seems like html tags needs different treatment?

I filled t.html with 100 lines of the same content (each line is just <h1>Test Page 1</h1> . For this demonstration I used nl t.html | grep 88; to show the 88th line. ( nl just numbers each line, and grep searches for a regular expression to match, but 88 just matches a literal 88). I run that at the beginning and the end of my command, to show line 88 before and after the change.

$ nl t.html | grep 88; sed -i -e '88 s/Page 1/Page 10/' t.html; nl t.html | grep 88
    88  <h1>Test Page 1</h1>
    88  <h1>Test Page 10</h1>

You have to be careful with regular expressions - if you just use s/1/10/ it will replace the 1 in the first h1 instead of the 1 in Page 1 .

cat >> replace.ed << EOF
88s/e 1/e 10/
wq
EOF

ed -s index.html < replace.ed
rm -v ./replace.ed

Use

sed -E 's,(>[^<]*)1([^<]*<),\110\2,'

s,(>[^<]*)1([^<]*<),\110\2, will find > and any text other than < , then 1 , then any text other than < up to and including < , and replaces the match with the text before 1 , then 10 , then the text after 1 .

Nice little one liner:

cat data.txt | awk 'NR==2'| sed 's/Test Page 1/Test Page 10/'

So the AWK command uses NR, which is the total number of input lines seen so far. Change this to the specific line number in question. The sed command literally just swaps everything inbetween the first and last slashes.

Hopefully that helps:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM