for example qa_sharutils-2009-04-22-15-20-39
, want chop last 20 bytes, and get 'qa_sharutils
'.
I know how to do it in sed, but why $A=${A/.\{20\}$/}
does not work?
Thanks!
To access the last n characters of a string, we can use the parameter expansion syntax ${string: -n} in the Bash shell. -n is the number of characters we need to extract from the end of a string.
In this method, you have to use the rev command. The rev command is used to reverse the line of string characterwise. Here, the rev command will reverse the string, and then the -c option will remove the first character. After this, the rev command will reverse the string again and you will get your output.
In bash, a string can also be divided without using $IFS variable. The 'readarray' command with -d option is used to split the string data. The -d option is applied to define the separator character in the command like $IFS. Moreover, the bash loop is used to print the string in split form.
To access the last character of a string, we can use the parameter expansion syntax ${string: -1} in the Bash shell. In bash the negative indices count from the end of a string, so -1 is the index of a last character.
If your string is stored in a variable called $str, then this will get you give you the substring without the last 20 digits in bash
${str:0:${#str} - 20}
basically, string slicing can be done using
${[variableName]:[startIndex]:[length]}
and the length of a string is
${#[variableName]}
EDIT: solution using sed that works on files:
sed 's/.\{20\}$//' < inputFile
similar to substr('abcdefg', 2-1, 3) in php:
echo 'abcdefg'|tail -c +2|head -c 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With