Help with awk command

Guys, first post be kind! :slight_smile:

Need some guidance here

I plan to edit 3 xml files without opening them (as opening, editing, closing is more prone to errors).

The one I want to edit is with a condition.

I need to update N to Y wherever I see Flag_XYZ_TurnOn in all 3 files. Also I prefer to run it from command line rather than having it in a script.

Example of the pattern:

Before:

<Name>Flag_XYZ_TurnOn</Name>
<Value>N</Value>

After:

<Name>Flag_XYZ_TurnOn</Name>
<Value>Y</Value>

I wrote SED commands and it works great in Linux but NOT in Unix

I tried the following sed commands from command line

sed -i.saved '/Flag_xyz_/{n;s/N/Y/}'   infile_1  infile_2

sed '/Flag_xyz_/{n;s/N/Y/}'   input_file

So as an alternative to sed I tried looking at awk as it is compatible with Unix too. But instead of command line it is making to write a script example below, which am personally not prefering.

for i in `find . -type f -name "*.xml"`
do
awk '/Flag_xyz_TurnOn/{n=NR+1}NR==n{sub(/>N</,">Y<")}1' $i > /temp/tmp123.xml
cp /temp/tmp123.xml $i
rm /temp/tmp123.xml
done

Anybody can suggest me to write in a better way? So that its a single line command, which i can run from command line to achieve my desired result?

Thanking you in advance.

cheers

OK, so can we see what your working linux sed command line - and on what UNIX are you trying ? ( OS and Version...)

What linux version are you using?

sed -i.saved '/Flag_xyz_/{n;s/N/Y/}'

Drop -i on UNIX - it's a GNU thing.

Thanks for your reply.

uname -a

Linux xxxx 3.10.0-327.36.1.el7.x86_64 #1 SMP Wed Aug 17 03:02:37 EDT 2016 x86_64 x86_64 x86_64 GNU/Linux


uname -a

HP-UX xxxx B.11.31 U ia64 2391660905 unlimited-user license

SunOS xxxxx 5.10 Generic_139555-08 sun4v sparc SUNW,Sun-Fire-T200

when I try the sed commands on Unix it is giving me this error

 sed '/Flag_xyz_/{n;s/N/Y/}' yyy.xml
sed: Function /Flag_xyz_/{n;s/N/Y/} cannot be parsed.


 sed -i.saved '/Flag_xyz_/{n;s/N/Y/}' yyy.xml
sed: illegal option -- i
Usage: sed [-n] [-e script] [-f source_file] [file...]

Unix sed needs at least a ; before a closing }

sed '/Flag_xyz_/{n;s/N/Y/;}'

Some Unix sed have bugs with ; e.g. lables and nested { } are only possible with multi-line.

sed '
/>Flag_xyz_TurnOn</{
n
s/>N</>Y</
}' input_file

The for loop can take the file names

for i in infile_1 infile_2
do
  ...
cone

If you have a script you can loop over its arguments

for i
do
  ...
done
1 Like

Thank you for the tips. Will try them!