Linux grep обрезать строку

Arch Linux

I tested tail, head, basename and sed (complex) but I couldn’t find any solution.

I think there must be a simple solution

#2 2007-12-03 00:08:21

Re: How to cut Strings found by grep?

I think there must be a simple solution

echo pkgver=2.6.23.8 | cut -d= -f2

#3 2007-12-03 00:09:16

Re: How to cut Strings found by grep?

You can use cut to break it at the equals sign and then take the second field.

cat PKGBUILD | grep pkgver= | cut -d = -f 2

#4 2007-12-03 00:17:34

Re: How to cut Strings found by grep?

grep ^pkgver= PKGBUILD | cut -d= -f2

#5 2007-12-03 00:20:50

Re: How to cut Strings found by grep?

Offtopic, but I have to point out the useless use of cat — do this instead:

#6 2007-12-03 00:25:20

Re: How to cut Strings found by grep?

Offtopic, but I have to point out the useless use of cat — do this instead:

#7 2007-12-03 03:36:11

Cerebral Forum Fellow From: Waterloo, ON, CA Registered: 2005-04-08 Posts: 3,108 Website

Re: How to cut Strings found by grep?

One-liner in sed (don’t even need to use grep!):

$ sed -n "/pkgver=/ < s/pkgver=//; p >" PKGBUILD ^ ^ ^ ^ Tells sed to print the line ^ ^ ^ This part strips out pkgver= ^ ^This part does the grep for you ^ This part tells sed to print nothing unless told

Last edited by Cerebral (2007-12-03 03:41:13)

Источник

How to remove the last character from a bash grep output

What I want to do is I want to remove the trailing «;» as well. How can i do that? I am a beginner to bash. Any thoughts or suggestions would be helpful.

For the problem at hand, it could have been solve with just grep: COMPANY_NAME=$(grep -Po ‘(?<=company_name=)"[^"]*"' file.txt)

14 Answers 14

This will remove the last character contained in your COMPANY_NAME var regardless if it is or not a semicolon:

echo "$COMPANY_NAME" | rev | cut -c 2- | rev 
COMPANY_NAME=`cat file.txt | grep "company_name" | cut -d '=' -f 2 | sed 's/;$//'` 

@Anony-Mousse Yes, I know there are at least two ways to avoid cat here. I left in the cat in order to avoid changing the command line from the question beyond what was actually necessary to make it work.

Читайте также:  Use all cores linux

@Anony-Mousse Not really in all cases, simply grep without cat -v will hide invisible (e.g. malicious) characters, unix.stackexchange.com/questions/202198/…

foo="hello world" echo $ hello worl 

This just made my day because I was trying to make a quick and dirty list of websites we had TLS keys for. for L in `ls *key` ; do echo $ ; done

I’d use head —bytes -1 , or head -c-1 for short.

COMPANY_NAME=`cat file.txt | grep "company_name" | cut -d '=' -f 2 | head --bytes -1` 

head outputs only the beginning of a stream or file. Typically it counts lines, but it can be made to count characters/bytes instead. head —bytes 10 will output the first ten characters, but head —bytes -10 will output everything except the last ten.

NB: you may have issues if the final character is multi-byte, but a semi-colon isn’t

I’d recommend this solution over sed or cut because

  • It’s exactly what head was designed to do, thus less command-line options and an easier-to-read command
  • It saves you having to think about regular expressions, which are cool/powerful but often overkill
  • It saves your machine having to think about regular expressions, so will be imperceptibly faster

I’ve tested the other suggested solution and this seems as the best one (and a simple one!) for my use case. Thanks!

I believe the cleanest way to strip a single character from a string with bash is:

but I haven’t been able to embed the grep piece within the curly braces, so your particular task becomes a two-liner:

COMPANY_NAME=$(grep "company_name" file.txt); COMPANY_NAME=$

This will strip any character, semicolon or not, but can get rid of the semicolon specifically, too. To remove ALL semicolons, wherever they may fall:

To remove only a semicolon at the end:

Or, to remove multiple semicolons from the end:

For great detail and more on this approach, The Linux Documentation Project covers a lot of ground at http://tldp.org/LDP/abs/html/string-manipulation.html

Using sed , if you don’t know what the last character actually is:

$ grep company_name file.txt | cut -d '=' -f2 | sed 's/.$//' "Abc Inc" 

Don’t abuse cat s. Did you know that grep can read files, too?

The canonical approach would be this:

grep "company_name" file.txt | cut -d '=' -f 2 | sed -e 's/;$//' 

the smarter approach would use a single perl or awk statement, which can do filter and different transformations at once. For example something like this:

COMPANY_NAME=$( perl -ne '/company_name=(.*);/ && print $1' file.txt ) 

don’t have to chain so many tools. Just one awk command does the job

 COMPANY_NAME=$(awk -F"=" '/company_name/' file.txt) 

you can strip the beginnings and ends of a string by N characters using this bash construct, as someone said already

$ fred=abcdefg.rpm $ echo $ bcdefg 

HOWEVER, this is not supported in older versions of bash.. as I discovered just now writing a script for a Red hat EL6 install process. This is the sole reason for posting here. A hacky way to achieve this is to use sed with extended regex like this:

$ fred=abcdefg.rpm $ echo $fred | sed -re 's/^.(.*). $/\1/g' bcdefg 

In Bash using only one external utility:

IFS='= ' read -r discard COMPANY_NAME 

Assuming the quotation marks are actually part of the output, couldn’t you just use the -o switch to return everything between the quote marks?

COMPANY_NAME="\"ABC Inc\";" | echo $COMPANY_NAME | grep -o "\"*.*\"" 

Some refinements to answer above. To remove more than one char you add multiple question marks. For example, to remove last two chars from variable $SRC_IP_MSG, you can use:

cat file.txt | grep "company_name" | cut -d '=' -f 2 | cut -d ';' -f 1 

as linus torvalds says, one of the most difficult things to find in a programmer is «good taste», which is difficult to define. but since you would benefit from it i will do so in this case: because of the initial cat every element of the pipeline that does real work operates on its standard input and its standard output. the benefit is that you can replace the cat with some other pipeline that produces output similar to file.txt and you don’t have to change even a single character in the functional part of the pipeline. this allows drop-in pipeline reusability.

@Det fyb above (forgot to tag you, just like somebody might forget to remove the input argument when composing pipelines and wonder why the output isn’t as expected)

@randomstring, while I don’t really see this as you giving me a «piece of your mind» (I lol’d by the way) it’s rather extreme reusability to preserve the use of cat just to give you the possibility of changing it to something else later on. The only thing I could see it worth for is simplicity. If a user types grep pattern file , then I’m pretty damn sure he understands it’s that first part which reads the file and where he starts piping it.

Источник

[bash] обрезать строку вывода

Как можно взять например первые три или последние три символа вывода команды?

Re: [bash] обрезать строку вывода

Re: [bash] обрезать строку вывода

$ echo 123456789 | cut -c1-3 123 $ echo 123456789 | rev | cut -c1-3 | rev 789

Re: [bash] обрезать строку вывода

и head/tail и cut/rev не будут работать нормально с utf

Re: [bash] обрезать строку вывода

Re: [bash] обрезать строку вывода

Или даже grep $ echo "превед" | grep -Eo '^.' пре $ echo "превед" | grep -Eo '.$' вед

Re: [bash] обрезать строку вывода

Проблема умножить число символов на два(для utf8)?

Re: [bash] обрезать строку вывода

$ echo превед | cut -c1-2 п $ echo превед | cut -c1-3 п $ echo превед | cut -c1-4 пр $ echo превед | cut -c1-11 преве $ echo превед | cut -c1-12 превед

Re: [bash] обрезать строку вывода

$ echo 123превед | cut -c1-5 123п

Re: [bash] обрезать строку вывода

Про представление циферок-то я и забыл.

Re: [bash] обрезать строку вывода

$ echo abcпревед | cut -c1-5 -> abcп

(Если брать кириллицу и латиницу), кириллица 2 байта, остальное один 🙂

Re: [bash] обрезать строку вывода

Ладно, ладно, торможу. Ну не бывает у меня выхлопа команд, содержащего кириллицу :-). Кроме того, я привык именно к grep/sed, и проблему такую не должен был заметить anyway.

Похожие темы

  • Форум [bash] Как обрезать строку до первого разделителя? (2009)
  • Форум Bash Строки (2011)
  • Форум [bash] экранирование строки (2008)
  • Форум [bash] форматирование вывода (2009)
  • Форум Bash, обработка строки (2016)
  • Форум как обрезать строки? (2017)
  • Форум Bash. Обработка вывода (2013)
  • Форум bash обрезает строку в истории (2013)
  • Форум [Bash] Обрезает строки в конвейере (2012)
  • Форум Форматированный вывод bash (2014)

Источник

Примеры использования grep в Linux.

Сегодня я расскажу о возможностях утилиты grep. Изначально она появилась еще в UNIX и на данный момент является частью любого дистрибутива BSD, Mac OS, Linux. Предназначение ее — поиск строк согласно условию, описанному регулярным выражением.

Существуют модификации классического grep — egrep, fgrep, rgrep. Все они заточены под конкретные цели, при этом возможности grep перекрывают весь функционал.

Итак, посмотрим на утилиту поближе.

Самым простым примером использования команды является вывод строки, удовлетворяющей шаблону, из файла.

Например мы хотим найти строку, содержащую ‘user’ в файле /etc/mysql/my.cnf. Для этого воспользуемся следующей командой:

Мы нашли нужную нам строку, но как потом найти ее в самом файле? Для этого мы добавим указание номера строки с помощью ключа -b.

Ключ -i в примере выше делает наш поиск регистронезависимым.

Теперь давайте попробуем вывести содержимое этого конфига без комментариев:

Благодаря ключу -v мы исключаем строки с символом #. «^» означает, что «#» должна находиться в начале строки.

Ниже я привел пример команды, обрезающей комментарии всех видов, а также пустые строки:

grep часто используется в связке с программными каналами (pipes) для обработки вывода других утилит.

вернет список устройств, содержащих sd в названии.

вернет все файлы, имеющиеся в системе, содержащие в названии ‘lala’.

Раскраска grep.

Иногда удобно, когда искомое нами слово подсвечивается цветом.

Все это уже есть в grep, остается только включить. Для этого в команде можно использовать ключ —color=auto.

Искомая буква «a» подсветится цветом.

Для того, чтобы не писать каждый раз такой длинный ключ — создадим псевдоним grep в файле ~/.bashrc (Применимо только к bash):

Теперь надо перечитать конфигурацию bash:

Все, теперь подсветка искомого слова будет включена по умолчанию.

Регулярные выражения.

Регулярные выражения — мощный инструмент, используемый во многих утилитах Linux. grep — не исключение. С помощью этих выражений можно описать любую искомую строку.

С помощью «|» можно указать условие «или». В примере ниже grep выдаст все строки с вхождениями user или db. Для обработки подобных выражений необходимо использовать ключ -E или использовать egrep.

Символами ^ и $ мы можем указать местоположение искомого слова. ^ обозначает начало строки, $ — его конец.

Найдем все строки, начинющиеся на #

Теперь найдем все строки, заканчивающиеся на «!»

А теперь отобразим номера пустых строк:

Поиск строк, содержащих цифру:

Поиск строк с двумя цифрами подряд:

Найдем все строки из двух символов:

Как вы заметили, точка является спецсимволом. Для того, чтобы использовать точку и другие знаки в выражении, нам потребуется их экранировать символом .

Экранировать знак \ можно самим собой:

Теперь попробуем найти все ip адреса, указанные в формате XXX.XXX.XXX.XXX

Напоследок приведу маленькую таблицу с универсальными выражениями:

На этом все, спасибо за внимание.

Источник

Оцените статью
Adblock
detector