简体   繁体   中英

Use SED to replace string of fixed length at certain position - arbitrary pattern

Trying to replace a string of fixed length at certain position (a string of arbitrary numbers) with a specified string.

I have to :
for every line beginning with 1 , in the 4-13 columns, replace existing value with 123456789 where column 4 is a space. 123456789

so a sample file looks like this in the first line:

110 000000000000000000000000000000000000000

and i want

110 123456789000000000000000000000000000000

So far I have:

sed -i "/^1/ s/(.{10})/ 123456789/4" $DEST/$FILE_NAME$DATE.txt

This doesn't do anything though...

With sed :

sed '/^1/s/\(.\{4\}\)\(.\{9\}\)/\1123456789/' "$DEST/$FILE_NAME$DATE.txt"

The preceding regex /^1/ makes the following substitute command apply only to lines starting with a 1 .

The substitute command itself captures the first 4 chars 100<space> and the following 9 chars 000000000 into separate groups while keeping the first 4 chars and replacing the following nine chars by 123456789 .

Btw, if you have GNU sed, you might simplify the command to:

sed -r  '/^1/s/(.{4})(.{9})/\1123456789/' 

... which looks simpler for understanding, but is not portable across all different sed versions.

Using awk , simple to understand solution

awk '/^1/ {print substr($0,1,4)"123456789"substr($0,14)}' file
110 123456789000000000000000000000000000000

If line starts with 1 , print the 4 first characters + 123456789 + the rest of the line starting from 14 position.

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