3

I need a sentence if...else.. that verify if the filename curbing a string specifies in bash

for j in `ls `
do
    if [ "${j:(-3)}" == ".gz" ]; then
        Cmd="zcat"
    elif [ "${j:(-4)}" == ".bz2" ]; then
        Cmd="bzcat"
    else
        Cmd="cat"
    fi

    if [ $j ***contains*** "string1"]; then
        $cmd $j | awk -F"," '{print $4}' 
    elif [ $j  *contains*  "string2" ]; then 
        $cmd $j | awk -F"," '{print $2}'
    fi

done

3 Answers 3

8

Use double brackets, which support wildcards:

if [[ $j == *string1* ]]; then

Also, don't parse ls; use a glob instead:

Instead of

for j in `ls `

use

for j in *

If you wan't the match to be case-insensitive, you can set the shopt -s nocasematch option:

shopt -s nocasematch
if [[ $j == *string1* ]]; then
Sign up to request clarification or add additional context in comments.

2 Comments

I worked well thanks, now I can do it but only as non-case sensitive?
@user2456216 use the shopt -s nocasematch to do case-insensitive matches
2

The =~ operator does what you want.

I personally would use find and xargs though.

find . -name "*.gz" -print0 | xargs -I{} -0 gzip -dc {} | cut -f, -d4
find . -name "*.bz2" -print0 | xargs -I{} -0 bzip2 -dc {} | cut -f, -d4

Comments

1

Use bash's regex capabilities here. So instead of;

if [ $j ***contains*** "string1"]; then

Use:

if [[ "$j" =~ \bstring1\b ]]; then

PS: Note use of \b (word boundaries) to make sure you don't match string123 in $j.

Also instead of using ls:

for j in `ls `

You should better use:

for j in *

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.