Remove first character of a string in Bash
I need to calculate md5sum of one string (pathfile) per line in my ls
dump, directory_listing_file
:
./r/g4/f1.JPG
./r/g4/f2.JPG
./r/g4/f3.JPG
./r/g4/f4.JPG
But that md5sum should be calculated without the initial dot. I've written a simple script:
while read line
do
echo $line | exec 'md5sum'
done
./g.sh < directory_listnitg.txt
How do I remove the first dot from each line?
myString="${myString:1}"
Starting at character number 1 of myString (character 0 being the left-most character) return the remainder of the string. The "s allow for spaces in the string. For more information on that aspect look at $IFS.
You can pipe it to
cut -c2-
Which gives you
while read line
do
echo $line | cut -c2- | md5sum
done
./g.sh < directory_listnitg.txt
remove first n characters from a line or string
#method1) using bash
str="price: 9832.3"
echo "${str:7}"
#method2) using cut
str="price: 9832.3"
cut -c8- <<< $str
#method3) using sed
str="price: 9832.3"
cut -c8- <<< $str
#method4) using awk
str="price: 9832.3"
awk '{gsub(/^.{7}/,"");}1' <<< $str
Set the field separator to the path separator and read everything except the stuff before the first slash into $name
:
while IFS=/ read junk name
do
echo $name
done < directory_listing.txt
Different approach, using sed, which has the benefit that it can handle input that doesn't start with a dot. Also, you won't run into problems with echo
appending a newline to the output, which will cause md5sum to report bogus result.
#!/bin/bash
while read line
do
echo -n $line | sed 's/^.//' | md5sum
done < input
compare these:
$ echo "a" | md5sum
60b725f10c9c85c70d97880dfe8191b3 -
$ echo -n "a" | md5sum
0cc175b9c0f1b6a831c399e269772661 -