Need to split a string in bash after certain number of characters

20,212

Solution 1

echo "${var:8}"

will echo the contents of $var starting at the character 8 (zero-based).

To strip off anything starting at the first space:

data=${var:8}
echo "${data%% *}"

Solution 2

To get only certain characters, use cut:

 $ echo '1234567' | cut -c2-5
 2345

However, in your case awk looks like better option:

$ echo '  PV Size 10.39 GB' | awk '{ print $3 }'
10.39

It reads text as space/tab separated columns, so it should work perfectly fine

Solution 3

You could use cut:

$ echo "PV Name /dev/sda2" |cut -d " " -f 3
/dev/sda2
Share:
20,212
howtechstuffworks
Author by

howtechstuffworks

I am Student from an university in North East. I had a bad habit of coding in a language, just by seeing examples and browsing/googling syntax online, thats how I completed most of my assignments, but better late than never, I realized that this is a problem, when you go into research, where you need to think in terms of language and understand the underlying mechanisms to become a better coder, which is what after all, I am striving for. Anyways, I think I will learn more here, than I could ever contribute.

Updated on July 09, 2022

Comments

  • howtechstuffworks
    howtechstuffworks almost 2 years

    I am writing a bash script that will execute a command and store the value in a string variable, now I need to split the string after certain characters. Is there a way? I cannot use delimiters coz the format is kinda like this

      PV Name /dev/sda2
      PV Size 10.39 GB
    

    Here I need to get the /dev/sda2 and 10.39 GB(if possible, just 10.39 alone) and write it in a new file. I cannot use delimiter because the space is at first.. I have not done much bash scripting. Is there a way to do this?