sidnow
June 14, 2015, 6:42pm
1
I want to extract the filename from a string.
This is how I have the rawdata ina file
/home/sid/ftp/testing/abc.txt
/home/sid/ftp/tested/testing/def.txt
/home/sid/sftp/date/misc/hij.txt
i want a script which would provide me an output like this
Directory Filename
/home/sid/ftp/ abc.txt
/home/sid/ftp/tested/testing def.txt
/home/sid/sftp/date/misc hij.txt
All help appreciated.
Aia
June 14, 2015, 6:55pm
2
sidnow:
I want to extract the filename from a string.
This is how I have the rawdata ina file
/home/sid/ftp/testing/abc.txt
/home/sid/ftp/tested/testing/def.txt
/home/sid/sftp/date/misc/hij.txt
i want a script which would provide me an output like this
Directory Filename
/home/sid/ftp/ abc.txt
/home/sid/ftp/tested/testing def.txt
/home/sid/sftp/date/misc hij.txt
All help appreciated.
Actually, you can help yourself, if you want. Look at this example:
file_path="/home/sid/ftp/tested/testing/def.txt"
echo ${file_path%/*} # this will display the directory path
/home/sid/ftp/tested/testing
echo ${file_path##*/} # this will display the file name without path
def.txt
Set up a loop with each absolute path and you have your script.
sidnow
June 14, 2015, 7:07pm
3
When I put it in a loop it said bad substitution
This is the code
for i in `cat filename`
do
echo ${$i%/*} echo ${$i##*/}
done
It gave this error
bash: echo ${file_path%/*}:bad substitution
Aia
June 14, 2015, 7:17pm
4
sidnow:
When I put it in a loop it said bad substitution
This is the code
for i in `cat filename`
do
echo ${$i%/*}; echo ${$i##*/}
done
It gave this error
bash: echo ${file_path%/*}:bad substitution
That was a good try, but it has a couple syntax errors.
Remove the red `$' and add the red `;'
However, that would display path and file in two different lines.
Modify as:
for i in `cat filename`
do
printf "%s %s\n" ${i%/*} ${i##*/}
done
1 Like
sidnow
June 14, 2015, 7:21pm
5
Brilliant Aia! It worked, thanks
You can also use basename and the dirname to get the output
basename /tmp/abc.txt will give abc.txt
dirname /tmp/abc.txt will give /tmp
1 Like
aia:
That was a good try, but it has a couple syntax errors.
Remove the red `$' and add the red `;'
However, that would display path and file in two different lines.
Modify as:
for i in `cat filename`
do
printf "%s %s\n" ${i%/*} ${i##*/}
done
That is almost almost always the wrong way ro read the contents of a file. Not only is cat
unnecssary but it will break your script if any lines contain whitespace or other pathological characters. It should be:
while read i
do
printf "%s %s\n" "${i%/*}" "${i##*/}" ## note the quotes!
done < "$filename"
1 Like
also please use "basename" command it extract the file names
Do not use basename
. It is an external command that is an order of magnitude slower than using the shell's parameter expansion.
2 Likes
Thank you for making it clear.
sidnow
June 15, 2015, 6:59am
11
Thanks cfajohnson. I didnt realize those scenarios with cat.