Piduna
Piduna

Reputation: 637

Bash, cut word with dot character from string

I have a string:

Log for: squid.log.2017.11.13

I need to cut out squid.log. so that I see:

Log for: 2017.11.13

I tried to cut

echo "Log for: squid.log.2017.11.13" | cut -d'.' -f3-5

But I ended up with:

2017.11.13

How can I get the result I want?

Upvotes: 2

Views: 3745

Answers (4)

Berti
Berti

Reputation: 111

This solution is a bit more reusable than the previous ones offered:

awk '/^Log/{ split($3,x,"."); print $1" "$2" "x[length(x)-2]"."x[length(x)-1]"."x[length(x)] };'

This looks for all lines starting with Log, then grabs the 3rd column which contains squid.log.2017.11.13 and utilizes the the split built-in to break up the string in to array x using the . as the delimiter. Once we have our array x, we know that the last 3 values will always be the date, and this will work regardless of the rest of the string, (even if squid.log was something different) - we can use the length built-in to make sure we only get the last three elements.

Then we just print our reformatted string print $1" "$2" "x[length(x)-2]"."x[length(x)-1]"."x[length(x)] - reinserting the .'s in the appropriate places since they were stripped by using them as the split delimiter.

Output: Log for: 2017.11.13

Upvotes: 0

karakfa
karakfa

Reputation: 67537

awk to the rescue! a non-standard approach to break the monotony...

define the to be removed text as field separator and parse and print the input line.

$ echo Log for: squid.log.2017.11.13 | awk -F' squid\\.log\\.' '{$1=$1}1'

Log for: 2017.11.13

Upvotes: 2

Bohemian
Bohemian

Reputation: 425258

Use sed to remove the part you don't want:

echo "Log for: squid.log.2017.11.13" | sed 's/squid\.log\.//'

Upvotes: 2

Ronan Boiteau
Ronan Boiteau

Reputation: 10138

You can use sed to cut the unwanted part:

echo "Log for: squid.log.2017.11.13" | sed 's/squid\.log\.//'

Upvotes: 2

Related Questions