0

I have a file with more than 8000 rows. File is divided into sections, each section is labeled with text like ##C, ##T,##N. I have to modify some rows in the file. I used command SED to mark lines between these markers. I am new to Bash, so I would appreciate some help. I have to modify text between those markers

##C
##A - beginning marker (must be next row after ##C)
text lines, some of them I have to modify
text lines, some of them I have to modify
##B -end marker

So far I have this command to mark lines between markers

sed -e '/##A/,/##B/{}' file.txt

Lines are formatted like this:

ZDMAD BELCH 0 0 25 26 30 50

My goal is to change some columns at specific lines. For example: When the first column is ZDMAD change 3rd column to 15.

I used this solved question for my furthest progress

1 Answer 1

0

Since you know how to make sed act only between markers, your real problem is you cannot yet make it "change some columns". This can be tricky because sed doesn't know about columns.

For example: When the first column is ZDMAD change 3rd column to 15.

Perhaps this particular example may be solved in sed, but in a general case of manipulating columns awk is better because it splits records into fields and operates at this level of abstraction.

This works in my Debian:

awk '
BEGIN {
   marked=0
   markA="##A"
   markZ="##B"
}
$1==markZ {marked=0}
$1=="ZDMAD" && marked==1 {$3=15}
$1==markA {marked=1}
{print $0}
' file.txt

The procedure:

  1. Set useful variables at the beginning (i.e. just once); start in a "non-marked" state.

Then for every record:

  1. If the first field is the end marker, go to a "non-marked" state.
  2. If the condition is met while in a "marked" state, do the job.
  3. If the first field is the beginning marker, go to a "marked" state.
  4. Print the entire record.

Note the procedure checks for the end marker first, does the job and checks for the beginning marker last. The point is it shouldn't manipulate marker lines. In your example case the condition (ZDMAD) cannot match any marker line, so a different sequence wouldn't be a problem; but in general you should take this into consideration.

1
  • Thank you. I had to add some regex comparison, to ensure that lines with ##N and ##A are before the text, that I modify. But after while of trying it works. I am super new to awk or sed. I used to create only simle mostly backup scripts and they were part of Crontab. So thanks again for your response. :)
    – pesekvi
    Commented Jul 5, 2018 at 12:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .