Search code examples
bashsedls

Removing 2 last characters from a string


I'm trying to make a list of directories from two sources. The other directory has entries that can have -1 or -2 after them and I want to get rid of them.

ls output example:

something.something.anything-1
stuff.stuff.stuff.morestuff-2
st.uf.f

The code as how I have it now:

echo -e "\tDATA\t\t | \t\tSYSTEM"
for SYSTEM in `ls /system/app`; do
    for DATA in `ls /data/app | sed 's/-1*$//' | sed 's/-2*$//'`; do
        echo -n "$DATA | " 
    done
    echo "$SYSTEM"
done

It works just fine, but I'm currious if there's a better way of doing it, as I have to use sed twice. And I noticed there isn't really many good posts here to remove characters from strings using commands, this could be a good place to share your ideas.

UPDATE:

The updated code:

echo -e "\tDATA\t\t | \t\tSYSTEM"
for SYSTEM in `ls /system/app`; do
    for DATA in `ls /data/app | sed 's/-[[:digit:]]*$//'`; do
        echo -n "$DATA | " 
    done
    echo "$SYSTEM"
done

Wich works perfectly!


Solution

  • If you want to remove the last two chars always:

    echo "abcdefg" | sed 's/..$//g'
    > abcde
    

    Or you can use a tighter regex for all digits

    echo "abcdefg-2" | sed 's/-[[:digit:]]$//g'
    > abcdefg
    

    Or just those two:

    echo "abcdefg-2" | sed 's/-[12]$//g'
    > abcdefg