mcExchange
mcExchange

Reputation: 6494

Split string at special character in bash

I'm reading filenames from a textfile line by line in a bash script. However the the lines look like this:

/path/to/myfile1.txt 1
/path/to/myfile2.txt 2
/path/to/myfile3.txt 3

...

/path/to/myfile20.txt 20

So there is a second column containing an integer number speparated by space. I only need the part of the string before the space. I found only solutions using a "for-loop". But I need a function that explicitly looks for the " "-character (space) in my string and splits it at that point.

In principle I need the equivalent to Matlabs "strsplit(str,delimiter)"

Upvotes: 1

Views: 6289

Answers (5)

Jahid
Jahid

Reputation: 22428

This should work too:

line="${line% *}"

This cuts the string at it's last occurrence (from left) of a space. So it will work even if the path contains spaces (as long as it follows by a space at end).

Upvotes: 1

GHugo
GHugo

Reputation: 2654

Three (of many) solutions:

# Using awk
echo "$string" | awk '{ print $1 }'
# Using cut
echo "$string" | cut -d' ' -f1
# Using sed
echo "$string" | sed 's/\s.*$//g'

Upvotes: 2

Alex
Alex

Reputation: 1

while read -r line
do
   { rev | cut -d' ' -f2- | rev >> result.txt;  } <<< $line
done < input.txt

This solution will work even if you have spaces in your filenames.

Upvotes: 0

hek2mgl
hek2mgl

Reputation: 157947

If you need to iterate trough each line of the file anyways, you can cut off everything behind the space with bash:

while read -r line ; do
    # bash string manipulation removes the space at the end
    # and everything which follows it
    echo ${line// *}
done < file

Upvotes: 1

chepner
chepner

Reputation: 530970

If you are already reading the file with something like

while read -r line; do

(and you should be), then pass two arguments to read instead:

while read -r filename somenumber; do

read will split the line on whitespace and assign the first field to filename and any remaining field(s) to somenumber.

Upvotes: 3

Related Questions