Reputation: 301
I want to give a script a file path, take the file name, assign the file name to a variable, then perform an action to the file at the file path.
Unfortunately, I do not know how to access the string content of the variable, instead of the file being held at the file path.
TestingScript.sh:
#!/bin/bash
egrep -o "[^/]+$" ${1} #get name of the file from the end of the filepath
wc -l $1 #count the number of lines in the file
Testing.txt
This
/is
the
text
Running it:
./TestingScript.sh "/User/Me/Directory/Testing.txt"
Instead of this returning:
Testing.txt
4 /User/Me/Directory/Testing.txt
This is the output:
/is
4 /User/Me/Directory/Testing.txt
Upvotes: 0
Views: 104
Reputation: 754860
Converting comments into an answer.
Running echo "$1" | grep -E -o '^/.+
' would run grep -E
(aka egrep
) on the name, but the regex doesn't match the last component of the name (you'd need '[^/]+$'
for that, and the name couldn't end with a /
). But the command you want is basename $1
(not least because basename /x/y/z/
reports z
and even the revised grep
regex fails on that). Incidentally, the -o
option to grep
(egrep
) is a GNU extension.
Why does this matter "The
-o
option togrep
(egrep
) is a GNU extension"?
Not all copies of grep
on the machines I use are GNU grep
— all the world is not a Linux box. And you would either get an error message or different behaviour if the version of grep
on the non-Linux box either does not support the -o
option at all or does not use the option with the same meaning as GNU grep
does. If you only work on Linux boxes, you don't have to worry about it; that's why it was an incidental comment.
I did not have an issue with
'[^/]+$'
— why do you say it fails?
Because echo /x/y/z/ | grep -o -E '[^/]+$'
gives no output. If there is no trailing slash (which is used to force the name to be a directory), then there's no problem. It's a case of extremism — how can your script be broken by extreme inputs. If /x/y/z/
was a directory (or didn't exist), the wc
command would fail too.
Upvotes: 1