V
V
Vadim Durov2018-11-16 00:19:14
linux
Vadim Durov, 2018-11-16 00:19:14

How to output a snippet from a text file in BASH?

I've been sitting for 5 hours now and I can't even come up with an algorithm by which this script would work.
I ask for your help)
The task itself:
The script outputs a fragment of a file coming to the standard input. The fragment is specified as a rectangular block with the specified coordinates in symbols (from 0). The command line specifies the upper left corner of the block and the lower right. First the line number, then the column. Do not use the cut command!
Example:
$ cat example.txt
The priest had a dog,
he loved it.
She ate a piece of meat.
He killed her.
$./myscript.sh 1 3 3 7 < example.txt
her lyu
ate
her ub

Answer the question

In order to leave comments, you need to log in

4 answer(s)
X
xotkot, 2018-11-16
@picturax

myscript.sh

#!/usr/bin/env bash

x1=$1; y1=$2
x2=$3; y2=$4
x=0
while read line
do
  if (( $x >= $x1 && $x <= $x2 )); then
    echo "${line:$y1:$[y2-y1+1]}"
  fi
  x=$[x+1]
done

rough version, if desired, you can optimize

J
jcmvbkbc, 2018-11-16
@jcmvbkbc

#! /bin/sh

TOP=$(($1 + 1))
BOT=$(($3 + 1))

LEFT=$2
WIDTH=$(($4 - $2 + 1))

sed -n "$TOP,$BOT s/.\{0,$LEFT\}\(.\{0,$WIDTH\}\).*$/\1/p"

$ ./win.sh 1 3 3 7
У попа была собака,
Он её любил.
Она съела кусок мяса.
Он её убил.
её лю
 съел
её уб
$

D
Dmitry Shitskov, 2018-11-16
@Zarom

Substring Extraction section https://www.tldp.org/LDP/abs/html/string-manipulat...
${string:position:length}
Easy as hell!

X
xtress, 2018-11-16
@xtress

Dig from:
ps
It should be something like this, in the morning, as soon as I get to the laptop, I will say more precisely

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question