Linux split by space

how to split the string after and before the space in shell script?

In addition to jasonwryan’s suggestion, you can use cut :

The above cut s the echo output with a space delimiter ( -d’ ‘ ) and outputs the first field ( -f1 )

@surbhi What says command not found? cut is a standard utility. Your script probably has an error somewhere else. More generally, never say “it is not working”. Always say exactly what code you ran, exactly what happened, and copy-paste error messages.

This answer should be accepted, as it’s the most concise and direct way. It won’t work in cases that are more complicated than the given example, of course.

A neat way to do this is to use a bash array to split up a string on spaces. You can declare an array simply by using brackets:

var="129 148 181" vars=( $var ) echo "First word of var: '$'" echo "Second word of var: '$'" echo "Third word of var: '$'" echo "Number of words in var: '$'" 

It depends on you using bash. If you are using a different shell it may not work. echo $SHELL should show: /bin/bash or similar.

This does work in ZSH zoom=»one two three»; declare -a zoomie=( $( echo $zoom | cut -d’ ‘ -f1- ) ); echo $;

Works in zsh for me, but I had to use command substitution and echo inside the array: vars=( $(echo $) )

TL;DR

$ echo "$var" 129 148 $ echo "$" 129 

Commentary

While there are a bazillion ways to answer your question, the simplest is Parameter Expansion, which is what Jason suggested in the comments. I believe it is right tool for this exact question.

The other answers here (piping to cut and splitting into an array) are not wrong, by the way. They are versatile solutions that make it easier when your next question is, “So, how do I get the 2nd or nth number?” Simple problems rarely stay simple for long.

Downsides

This method might not work everywhere, though I’m hard pressed to find a place it doesn’t. It of course works in bash , the default interactive shell on most Unix boxes, and zsh , which is the default in MacOS. Even limited shells you’ll find on routers, such as ash and dash , which I expected to break, work fine with Parameter Expansion.

Sidenote about $ versus $

You may have noticed that I used two percent signs instead of one as Jason had suggested. The difference is %% deletes the longest matching string and % the shortest. For example, if var contained three numbers, you’d see this:

$ echo "$var" 129 148 167 $ echo "$" 129 $ echo "$" 129 148 

For Further Reading

If you’ve made it this far, you’re probably wondering, “Where can I learn more about this magic called Parameter Expansion?” The answer is, in the documentation for your shell, e.g., man bash . Here is an extract from the section on Parameter Expansion from the bash manpage:

Remove matching prefix pattern.

The word is expanded to produce a pattern just as in pathname expansion, and matched against the expanded value of parameter using the rules described under Pattern Matching. If the pattern matches the beginning of the value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ‘#’ case) or the longest matching pattern (the ‘##’ case) deleted. If parameter is @ or *, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.

Читайте также:  Linux mint удаление драйвера nvidia

Remove matching suffix pattern.

The word is expanded to produce a pattern just as in pathname expansion, and matched against the expanded value of parameter using the rules described under Pattern Matching. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ‘%’ case) or the longest matching pattern (the ‘%%’ case) deleted. If parameter is @ or *, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.

Источник

Bash Split String Examples

We need to split the string data for various purposes in the programming. Many programming languages have a built-in function named ‘split’ for divide any string data into multiple parts. But there is no built-in function in bash for dividing the string. Normally, single or multiple delimiters are used to split any string data. How you can split the string in bash is shown in this tutorial by using different examples.

Using $IFS variable

The special shell variable $IFS is used in bash for splitting a string into words. $IFS variable is called Internal Field Separator (IFS) that is used to assign the specific delimiter for dividing the string. Word boundaries are identified in bash by $IFS. White space is the default delimiter value for this variable. Any other value like ‘\t’, ‘\n’, ‘-‘ etc. Can be used as the delimiter. After assigning the value into $IFS variable, the string value can be read by two options. These are ‘-r’ and ‘-a’. The option, ‘-r’ is used to read backslash(\) as a character rather than escape character and ‘-a’ option is used to store the split-ted words into an array variable. The string can be split-ted without using $IFS variable in bash. Different ways to split string data (with $IFS or without $IFS) are shown in the following examples.

Example-1: Split string based on space

The string value is divided by white space by default. Create a file named ‘split1.sh’ and add the following code. Here, $text variable is used to assign a string value. The shell variable, $IFS is used to assign the character that will be used for dividing the string data. Space is used in this script as the separator. ‘-a’ option is used with reading command to store the split-ted data into an array variable named $strarr. ‘for’ loop is used to read each element of the array, $strarr.

Читайте также:  Linux включить сетевое обнаружение

#Define the string value
text = «Welcome to LinuxHint»

# Set space as the delimiter
IFS = ‘ ‘

#Read the split words into an array based on space delimiter
read -a strarr

#Count the total words
echo «There are $ words in the text.»

# Print each value of the array by using the loop
for val in » $ » ;
do
printf » $val \n »
done

The following output will appear after running the script.

Example-2: Split string based on a particular character

Any specific character can be used as the separator for dividing the string value. Create a file named split2.sh and add the following code. Here, book name, author name and price value are taken by adding comma(,) as an input string. Next, the string value is split-ted and stored in an array based the value of the shell variable, $IFS. Each value of the array elements is printed by the index value.

#Read the string value
echo «Enter book name, author name and price by separating comma. »
read text

# Set comma as delimiter
IFS = ‘,’

#Read the split words into an array based on comma delimiter
read -a strarr

#Print the splitted words
echo «Book Name : $ »
echo «Author Name : $ »
echo «Price : $ «

The following output will appear after running the script.

Example-3: Split the string without $IFS variable

This example shows how the string value can be divided without using $IFS in bash. Create a file named ‘split3.sh’ and add the following code. According to the script, a text value with the colon(:) has to take as input for splitting. Here, ‘readarray’ command with -d option is used to split the string data. ‘-d’ option is used to define the separator character in the command like $IFS. Next, ‘for’ loop is used to print the array elements.

#Read the main string
echo «Enter the string with colon(:) to split»
read mainstr

#Split the string based on the delimiter, ‘:’
readarray -d : -t strarr printf » \n «

# Print each value of the array by using loop
for ( ( n = 0 ; n < $; n++ ) )
do
echo » $ »
done

The following output will appear after running the script.

Example-4: Split the string with a multi-character delimiter

The string value is split-ted by a single character delimiter in all previous examples. How you can split the string by using multi-character delimiter is shown in this example. Create a file named ‘split4.sh’ and add the following code. Here, $text variable is used to store a string data. $delimiter variable is used to assign a multi-character data that is used as the delimiter in the next statements. $myarray variable is used to store each split-ted data as an array element. Finally, all split-ted data are printed by using ‘for’ loop.

#Define the string to split
text = «learnHTMLlearnPHPlearnMySQLlearnJavascript»

#Define multi-character delimiter
delimiter = «learn»
#Concatenate the delimiter with the main string
string = $text $delimiter

#Split the text based on the delimiter
myarray = ( )
while [ [ $string ] ] ; do
myarray+= ( » $ » )
string = $
done

#Print the words after the split
for value in $
do
echo -n » $value »
done
printf » \n «

The following output will appear after running the script.

Conclusion:

The string data need to split for different programming purposes. Various ways of splitting string data in bash are shown in this tutorial. Hope, after practicing the above examples, the readers will be able to split any string data based on their requirement.

Читайте также:  Installing java in linux 64 bit

For more information watch the video!

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Split a sentence using space in bash script

How can I split a sentence using space, and print from second word onwards? For example, if my sentence is Hello World Good Morning , then I want to print like:

Why you posted the expected output like this? All the wonderful answers here target the above expected output only.

7 Answers 7

$ echo "Hello World Good Morning" | cut -d' ' -f2- World Good Morning 

This tells cut to «cut» (surprisingly) based on d elimiter space and print from 2nd field up to the end.

$ echo "Hello World Good Morning" | sed 's/^[^ ]* //' World Good Morning 

This gets, from the beginning of the line ( ^ ), a block of characters not containing a space ( [^ ]* ) and then a space and replaces it with empty content. This way, the first word is deleted.

$ while IFS=" " read -r _ b; do echo "$b"; done  

This sets the field separator to the space and reads the first block in a dummy variable _ and the rest in the variable $b . Then, it prints $b .

$ echo 'Hello World Good Morning' | awk '/,"")>1' World Good Morning 

This replaces 1 block of not space characters + block of spaces with an empty string.

Unsure if it was a typo on OP's part, but his output has a lower case w also his output has a newline after every word

You can change the record separator to a space in awk and print from the second record onwards:

As pointed out in the comments, there is also an extra blank line at the end of the output. This comes from the newline at the end of the input. If you are using GNU awk, it can be suppressed by setting the record separator to the [[:space:]] character class:

Alternatively, as suggested by fedorqui, you can use printf instead of echo to pass the variable to awk:

printf '%s' 'Hello World Good Morning' | awk 'NR>1' RS=' ' 

@fedorqui also a good suggestion, although I think that it's a good idea to use a format specifier in general. I've edited to include it, thanks.

You can use the split+glob operator:

sentence="Hello World Good Morning" set -f # disable the glob part IFS=" " # split on space characters: set -- $sentence # apply the split+glob operator # (leaving a variable expansion unquoted) 

Now $1 contains Hello . $4 contains Morning .

shift 1 # (or just "shift") shifts the positional parameters by 1 printf '%s\n' "$@" # print them 

Note that it splits on sequences of space character and ignores the leading and trailing ones.

The above works in any Bourne-like or POSIX shell except zsh , not just bash . With zsh , there's no implicit split+glob operator upon variable expansion unless in sh emulation. There is an explicit split $=var and explicit glob $~var operator. So in zsh :

sentence="Hello World Good Morning" IFS=" " set -- $=sentence shift printf '%s\n' "$@" 
words=($=sentence) printf '%s\n' $words[2,-1] 

zsh also has variable expansion flags including a s one to split on a given string, and a more consistent way to nest variable expansions than in other shells, so:

$ printf '%s\n' $<$<(s: :)sentence>[2,-1]> World Good Morning 

Источник

Оцените статью
Adblock
detector