jake9115
jake9115

Reputation: 4084

Trying to grep part of a file name in shell script?

I have a very simple grep problem but can't seem to solve it. I have several files like this:

sample.txt
sample7.doc.txt
another_sample.sample.lst.txt
three.txt

...And I just want to grab everything before the ".txt". I was trying to do this in shell script like this:

ame=`echo $1 | grep -Po "^[A-Za-z0-9]+"`

...But of course that returns only the portion up until the first 'dot'. Can someone please help modify this regex?

Upvotes: 2

Views: 1886

Answers (4)

a.saurabh
a.saurabh

Reputation: 1231

Here is the script for renaming file.

Pass file name as argument

!/bin/bash

mv $1 $(echo $1 | awk -F.txt '{print $1}')

Upvotes: 0

Fredrik Pihl
Fredrik Pihl

Reputation: 45652

No need for regexp:

$ basename sample.txt .txt
sample

or using any POSIX-compatible shell:

$ echo "$a"
sample.txt

$ y=${a%.txt}

$ echo "$y"
sample

Upvotes: 7

xoid
xoid

Reputation: 1134

  1. remove .txt

    name=echo $1|sed 's/.txt$//'

  2. use basename

    name=echo $fullname|basename .txt

Upvotes: 0

Kent
Kent

Reputation: 195039

try this:

grep -Po '.*(?=\.txt$)'

Upvotes: 1

Related Questions