Reputation: 1119
I've tried googling for the answer to my question, and i'm sure the answer is out there, I just don't know what to search. Basically what i'm trying to do is take a line from a file grab the last 2 fields (seperated by "\
") and then print those two fields.
However, I want these fields to be printed out with 2 backslashes in beween them. (i'm working with windows path's) Here's my statement
$ line = C:\Windows\System32\folder1\folder2\folder3\executable.exe
$ echo $line | awk -F "\\" '{print $(NF-2)$(NF-0)}'
I want the output to return folder3\\executable.exe
My experience with awk is limited. Thank you in advanced for any help
Upvotes: 3
Views: 5293
Reputation: 2731
You can also use rev
for reverse the string, split your string on the '\' separator and then take the first two string in the array.
In the end, compose the string with the previous separator '\' and reverse again.
The reverse is necessary because you can't always know the numbers of sub-directory between the root and the last one.
Upvotes: 0
Reputation: 143047
From the command line:
$ echo $line | awk 'BEGIN{FS="\\"; OFS="\\\\"} {print $(NF-1), $NF}'
will give you
folder3\\executable.exe
for your line
FS
sets the field separator for the line(s) processed, OFS
the output field separators. The double \\
are necessary to escape the special meaning of the single \
.
Note that your assignment to line
should enclose the string in ""
with no spaces before/after the =
. I.e.,
line="C:\Windows\System32\folder1\folder2\folder3\executable.exe"
Alternatively, this script (so.awk)
BEGIN { FS="\\"
OFS="\\\\"}
{print $(NF-1), $NF}
will give you the same output if invoked as echo $line | awk -f so.awk data.txt
where data.txt
contains your one (or possibly more) path(s)
Update:
In case you should want to print leading double backslashes: print "", $(NF-1), $NF
will do the trick by adding an empty string at the start, as mentioned in a helpful comment by @Dennis Williamson
Upvotes: 2