Hello lad
Hello lad

Reputation: 18790

How to split a string by pattern into tokens using sed or awk

My input is

filename.b.c

The output I want is

filename
b
c

Can I split by the '.' character using sed or awk?

Upvotes: 3

Views: 8407

Answers (4)

Froggiz
Froggiz

Reputation: 683

You can replace . with a space, and then use () to set it as array:

filename=file.a.b.c
arr=(${filename//./ })

then you can display your array:

for k in "${arr[@]}";do echo "[$k]";done

Upvotes: 2

Mateusz Kleinert
Mateusz Kleinert

Reputation: 1376

As the question was about sed and awk, here's the sed version:

echo filename.b.c | sed 's/\./\n/g'

And the awk version:

echo filename.b.c | awk -F'.' '{for (i=1; i<= NF; i++) print $i}'

Upvotes: 6

anubhava
anubhava

Reputation: 784898

You can do this using BASH string manipulations:

s='filename.b.c'
eol=$'\n'

echo "${s//./$eol}"
filename
b
c

Or using read with IFS:

IFS=. read -ra var <<< "$s"
printf "%s\n" "${arr[@]}"
filename
b
c

Upvotes: 3

choroba
choroba

Reputation: 241758

You can use tr:

echo filename.b.c | tr . '\n'

Upvotes: 5

Related Questions