0

I am trying to use the file separator as "~" but somehow it is not working properly, where as other delimiter such as ",", "|" are working as expected. I mean there is no error but I am not getting desired output.

I am trying with the same data in "example.txt" file I have added 2 rows which are delimitd by ~, and then changed it to |.

Also main intention is to add the splitted name at the end of the record (interedsted only in newmodifiedline) rest i am just trying to test the values.

awk code :

awk 'BEGIN { FS = "~" } ; {line=$0}; {fullname=$1}; {split(fullname, a, " ")}; {arrysize=length(a)}; {newmodifiedline=line"~"a[1]"~"a[2];}; {print fullname, arrysize, a[1], a[2], "-->",newmodifiedline}' example.txt
shellter
  • 36,525
  • 7
  • 83
  • 90
Mayank Tripathi
  • 489
  • 5
  • 16
  • Same result when you specify the delimiter outside the statement? E.g. `awk -F'~' 'BEGIN {line=$0}; {fullname=$1}; {split(fullname, a, " ")}; {arrysize=length(a)}; {newmodifiedline=line"~"a[1]"~"a[2];}; {print fullname, arrysize, a[1], a[2], "-->",newmodifiedline}' example.txt` – jared_mamrot Jan 05 '21 at 22:55
  • 6
    `echo 1~2 | awk -v FS="~" '{print $2}'` seems to work just fine. Please, show some sample data with the expected output. _somehow it is not working properly_ is not really informative. – James Brown Jan 05 '21 at 22:55
  • 3
    The semicolons on your command line puzzle me — I'd not write them there. I also wouldn't write the whole script on a single line. You seem to have 1 BEGIN statement and 6 statements each executed per line of input. It would be more conventional to use one set of braces around the 6 statements, which would need to be separated by semicolons if you keep the code on a single line. IMO, readability would be greatly improved if you could actually see the whole script without scrolling. You'd put the statements on separate lines. – Jonathan Leffler Jan 05 '21 at 23:55
  • 1
    Could it be possible that your lines end with CRLF (`\r\n`) and not just an LF (`\n`)? This is generally the culprit with good awk behaving awkwardly. Have a look at [Why does my tool output overwrite itself and how do I fix it?](https://stackoverflow.com/q/45772525/8344060) – kvantour Jan 06 '21 at 07:42
  • @JonathanLeffler - I am new to awk, and on some site I learned to do the multiple statements in one go... Here the main intention is to pick the first field and split it based on some space delimiter and then append this splitted values at the end of each respective record / line. Thus it has so many statements. Please guide the correct way, might be that solve the issue i am facing. Thanks – Mayank Tripathi Jan 06 '21 at 18:47

1 Answers1

3

This works both with POSIX and GNU awk:

echo '1~2~3' | awk -v FS="~" '{print $2}'
echo '1~2~3'| awk 'BEGIN{FS="~"} {print$2}'

Both print 2 as expected.

dawg
  • 98,345
  • 23
  • 131
  • 206