Reputation: 13
I have read some threads about extracting some parts from filename, but still cannot solve my problem.
There are some files named aa - bb.txt
, cc - dd.txt
, ee - ff.txt
, etc.
And the last line in every file is like this:
somewordbbaa
for aa - bb.txt
and for cc - dd.txt
is:
somewordddcc
Then in ee - ff.txt
is:
somewordffee
I want to write a shell script to delete the bbaa, ddcc, ffee in last line of the respective file. I have tried following:
#!/bin/bash
for file in *.txt
do
artist=`echo $file | awk -F'[ .]' '{print $1}'`
name=`echo $file | awk -F'[ .]' '{print $3}'`
echo $artist >> artist
echo $name >> name
sed -i "s/$name$artist//" $file
done
And after I ran it,it threw this
sed: can't read aa: No such file or directory
sed: can't read -: No such file or directory
sed: can't read bb.txt: No such file or directory
sed: can't read cc: No such file or directory
sed: can't read -: No such file or directory
sed: can't read dd.txt: No such file or directory
sed: can't read ee: No such file or directory
sed: can't read -: No such file or directory
sed: can't read ff.txt: No such file or directory
I also tried this
#!/bin/bash
ls *.txt | sed 's/\.txt//' > full_name
cut -f1 -d" " full_name > artist
cut -f3 -d" " full_name > name
for file in `ls -1 *.txt`, item1 in artist, item2 in name #Is this right?
do
tail -n -1 $file | sed 's/$item2$item1//' > $file.last #just the last line
done
It just showed this and had no reaction until pressing Ctrl+c
tail: cannot open `aa' for reading: No such file or directory
I think bash puts the blank of the filename as the separator, reads the $file
as aa
, -
, bb.txt
.
Can anyone give me some advice?
Upvotes: 1
Views: 113
Reputation: 528
Because your files have a space in the name, try your original script but change this line:
sed -i "s/$name$artist//" $file
to this:
sed -i "s/$name$artist//" "$file"
Upvotes: 1