Remove first character of a string in Bash

Viewed 170230

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?

8 Answers
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.

remove first n characters from a line or string

method 1) using bash

 str="price: 9832.3"
 echo "${str:7}"

method 2) using cut

 str="price: 9832.3"
 cut -c8- <<< $str

method 3) using sed

 str="price: 9832.3"
 sed 's/^.\{7\}//' <<< $str

method 4) using awk

 str="price: 9832.3"
 awk '{gsub(/^.{7}/,"");}1' <<< $str

There ia a very easy way to achieve this:

Suppose that we don't want the prefix "i-" from the variable

$ ROLE_TAG=role                                                                            
$ INSTANCE_ID=i-123456789

You just need to add '#'+[your_exclusion_pattern], e.g:

$ MYHOSTNAME="${ROLE_TAG}-${INSTANCE_ID#i-}"  
$ echo $MYHOSTNAME
role-123456789

You can do the entire thing like this:

% sh -c `sed 's@^.\(.*\)@md5sum \1@' <./dirlist.txt`

Really, I'm thinking you can make this a lot more efficient, but I don't know what is generating your list. If you can pipe it from that, or run that command through a heredoc to keep its output sane, you can do this whole job streamed, probably.

EDIT:

OK, you say it's from an "ls dump." Well, here's something a little flexible:

% ls_dump() {
> sed 's@^.\(.*\)$@md5sum \1@' <<_EOF_ | sh -s
>> `ls ${@}`
>> _EOF_
> }
% ls_dump -all -args -you /would/normally/give/ls
<desired output>

I think this calls only a single subshell in total. It should be pretty good, but in my opinion, find ... -exec md5sum {} ... + is probably safer, faster, and all you need.

EDIT2:

OK, so now I will actually answer the question. To remove the first character of a string in any POSIX compatible shell you need only look to parameter expansion like:

${string#?}

-Mike

Or like this

myString="${myString/.}"

Testing on Ubuntu 18.04.4 LTS, bash 4.4.20:

$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.4 LTS
Release:    18.04
Codename:   bionic

$ echo $BASH_VERSION
4.4.20(1)-release

$ myString="./r/g4/f1.JPG"
$ myString="${myString/.}"
$ echo $myString
/r/g4/f1.JPG
Related