Reputation: 53
I currently new to shell scripting and i am having an issue in replacing data. I need to replace the data of a specific column and row.
Below is a random database:
test:test1:test2:test3:test4
example:example1:example2:example3:example4
sample:sample1:sample2:sample3:sample4
for example, I would like to replace the word "test3" into "changed".. how do i achieve this? i tried several command like
awk -F : 'NR==n{$4=a}1' n="$row" a="$replace" test.txt
sed -i "$row"'s/\S\+/'"$replace"'/4' test.txt
although there is no error when i run those command, it did not replace my data either. anyone can give me some help on this problem..?
Upvotes: 0
Views: 2535
Reputation: 3464
Here is an sed
one-liner (using in-place editing):
#!/bin/bash
cat > /tmp/file <<EOF
test:test1:test2:test3:test4
example:example1:example2:example3:example4
sample:sample1:sample2:sample3:sample4
EOF
row=1
column=4
replace=changed
sed -i "$row"'s/^\(\([^:]*:\)\{'"$(($column - 1))"'\}\)[^:]*/\1'"$replace"'/' /tmp/file
cat /tmp/file
Upvotes: 0
Reputation: 74595
Your awk version works fine for me with a minor modification:
$ row=1
$ replace=changed
$ awk 'BEGIN{FS=OFS=":"}NR==n{$4=a}1' n="$row" a="$replace" file
test:test1:test2:changed:test4
example:example1:example2:example3:example4
sample:sample1:sample2:sample3:sample4
I have defined the Output Field Separator OFS
so that lines which are modified still have :
between each field. To overwrite the original file, you can just do awk '...' file > tmp && mv tmp file
.
Upvotes: 1