Home > database >  Bash: edit a file at a specific line and column regardless of keyword to replace
Bash: edit a file at a specific line and column regardless of keyword to replace

Time:09-23

I am trying to edit a numeric value in a file with sed command. I know the exact line and column of the value needs to change.

Let's say;

Line: 2, Column: 21

and this is the file I am trying to edit, i.e. example.txt

hello
this is my number = 131;
world

However, this numeric value may vary in terms of digits, e,g, 30 or 130.

If I want to set this number to 32,

how can I find and replace this numeric value? Assuming that I do not know the numeric value beforehand.

So far, I can only use sed with known keywords and lines;

sed -i '' -e '2s/131/32/' example.txt

CodePudding user response:

To replace anything at a particular offset, capture that many characters and replace everything after them.

sed -i '' -e '2s/^\(....................\).*/\132/' example.txt

Of course, if you can predict what those character are, try to be more specific:

sed -i '' -e '2s/^this is my number = .*/this is my number = 32/' example.txt

To replace any digits at the end of the indicated line, try

sed -i '' -e '2s/[0-9][0-9]* *$/32/' example.txt

(Your sed might have an -E or -r option which allows you to say .{20} instead of .....................)

CodePudding user response:

Using sed

$ sed -E '2s/(= ).*/\132/' input_file
hello
this is my number = 32
world

CodePudding user response:

In the assumption that there is always a white space that separates the last column/field, which is what your sample/data looks like, Something like:

sed '2s/[0-9]\{1,\}.$/32/' file.txt 

  • [0-9] is a Bracket Expression pattern/regex that means any digit/number.

  • {1,} is a quantifier that means one or more, the \ is just for escaping the { and }, since sed defaults to BRE.

  • A dot . means any character/string that should match the trailing ; in your pattern, change it to a ; to match a a literal ;.

  • $ is an anchor which means at the end.

  • Related