`awk -F_ "{print $1}"` not removing everything before the underscore in each line

1

I'm using Mac. I have a directory in which the files have names like ABC_2016-06-08_09-23.csv. I want to extract the part of each file name before the first underscore. I tried doing ls | awk -F_ "{print $1}" but I got back the full file names. What am I doing wrong?

jkabrg

Posted 2016-10-26T08:13:58.580

Reputation: 113

Answers

1

The problem here is that you are using double quotes instead of single quotes, so the correct is:

awk -F_ '{print $1}'

When you use double quotes, the shell expands $1 to whatever is defined. If it is nothing, it expands to nothing and hence you get a simple {print} that prints the whole line.

$ echo "$1"

$ echo "hello_you" | awk -F_ "{print $1}"
hello_you
$ echo "hello_you" | awk -F_ '{print $1}'
hello

And see how we can make it useful on some way:

$ myvar="ueee"
$ echo "hello_you" | awk -F_ "{ueee=23; print $myvar}"
23

fedorqui

Posted 2016-10-26T08:13:58.580

Reputation: 1 517