0

I have the following file

Field1|Field2|Field3|Field4|Field5
a|b|c|d|e
1|2|3|4|5
z|y|x|w|v

I have a script which accepts two inputs

script.sh Field3 T

The script.sh would take the 'Field3' argument and based on that column number should replace the contents with 'T'.

[edit]

I tried the following suggestion from @Costas and ran into a problem. My file is like this:

MODULE_ColumnA~MODULE_ColumnB~MODULE_ColumnC~MODULE_ColumnD~MODULE_ColumnE
8.2~Y~N~~0

If I run the following script

cat <filename> | awk -F'~' -v p='MODULE_ColumnD' -v r='99' 'NR==1{for (i=1;i<=NF;i++) if($i==p)f=i;print;next}$f=r'

It replaces the value, but the delimiter is missing or replaced with space in the output as such:

MODULE_ColumnA~MODULE_ColumnB~MODULE_ColumnC~MODULE_ColumnD~MODULE_ColumnE
8.2 Y N 99 0

How do I get back the delimiter in the records?

4
  • Why don't you pass 3 instead of Field3?
    – cuonglm
    Mar 5 '15 at 17:29
  • @cuonglm I just pasted an example to make it simpler to explain, in the actual file, the column headers are named differently and do not have the numeric suffix to them.
    – rahul
    Mar 5 '15 at 17:42
  • 1
    I mean if you pass the column number, it's easier awk -F'|' -v f=3 -v v=T 'FNR>1{$f=T}1' OFS='|' file
    – cuonglm
    Mar 5 '15 at 17:51
  • @cuonglm Thanks, yes it will make it easier. But the file has about 30 columns, and this script will be used as an utility for other users. So i wanted to make it simpler for them to use.
    – rahul
    Mar 5 '15 at 17:58
3
awk -F'|' -v p='Field3' -v r='T' '
    NR==1{
        for (i=1;i<=NF;i++)
            if ($i==p)
               f=i
        print
        next}
    $f=r
'

If you like to format it to use like script.awk save it like:

#!/usr/bin/awk -f
BEGIN{
    OFS=FS="|"}
NR==1{
    for (i=1;i<=NF;i++)
        if ($i==p)
            f=i
    print
    next}
$f=r

and make its executable by chmod +x script.awk and use:

./script.awk p=Field4 r=T input.file
2
  • I ran into another problem while trying your suggestion. Unfortunately I'm not able to add the explanation as a comment, so I`ve edited my question to include details.
    – rahul
    Mar 9 '15 at 13:26
  • 1
    @rahul If you use variant with -F'~' option add -v OFS='~' (Output Field Separator)
    – Costas
    Mar 9 '15 at 15:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.