Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to chop last n bytes of a string in bash string choping?

Tags:

bash

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!

like image 957
jaimechen Avatar asked Jun 23 '09 03:06

jaimechen


People also ask

How do I get the last 4 characters of a string in Bash?

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.

How do I remove the last 4 characters from a string in Unix?

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.

How do I cut a string in Bash?

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.

How do you get the last character of a string in a shell?

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.


2 Answers

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
like image 147
Charles Ma Avatar answered Sep 28 '22 08:09

Charles Ma


similar to substr('abcdefg', 2-1, 3) in php:

echo 'abcdefg'|tail -c +2|head -c 3
like image 30
diyism Avatar answered Sep 28 '22 08:09

diyism